package jndi;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

public class JndiFactory {
	
	
	private static JndiFactory instance = new JndiFactory();
	
	private static Logger jLog = Logger.getLogger(JndiFactory.class);
	
	
	public static JndiFactory getInstance() {
		
		return instance;
	}
	
	
	public Connection getConnection(String datenbank) {
		
		Connection connection = null;
		
		try {
			Context initContext = new InitialContext();
			
			Context envContext = (Context) initContext.lookup("java:/comp/env");
			
			DataSource ds = (DataSource) envContext.lookup(datenbank);
			
			connection = ds.getConnection();
		
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return connection;
	}
	
	
	public static void closeConnection(Connection connection) {
		
		if (connection != null) {
			try {
				connection.close();
				connection = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	
	public static String getEnvironmentAsString(String envName)
			throws NamingException {

		String env = null;

		InitialContext ictx = new InitialContext();
		Context myenv = (Context) ictx.lookup("java:comp/env");

		try {
			env = (String) myenv.lookup(envName);
		} catch (NamingException n) {
			jLog.info("String Environment '" + envName + "' is missing.");
		}

		return env;
	}

}
